package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WemediaConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.thread.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.service.WmNewsMaterialService;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author: zhk
 * @since: 2025/7/4
 */
@Slf4j
@Service
@Transactional
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMaterialService wmNewsMaterialService;

    @Override
    public ResponseResult lists(WmNewsPageReqDto wmNewsPageReqDto) {
        wmNewsPageReqDto.checkParam();
        LambdaQueryWrapper<WmNews> lqw = new LambdaQueryWrapper<WmNews>();
        log.info(wmNewsPageReqDto.toString());
        lqw.eq(null != wmNewsPageReqDto.getStatus(),WmNews::getStatus,wmNewsPageReqDto.getStatus())
                .eq(null != wmNewsPageReqDto.getChannelId(),WmNews::getChannelId,wmNewsPageReqDto.getChannelId())
                .between(null != wmNewsPageReqDto.getBeginPubDate() && null != wmNewsPageReqDto.getEndPubDate(),WmNews::getPublishTime,wmNewsPageReqDto.getBeginPubDate(),wmNewsPageReqDto.getEndPubDate())
                .like(StringUtils.isNoneBlank(wmNewsPageReqDto.getKeyword()),WmNews::getTitle,wmNewsPageReqDto.getKeyword())
                .eq(WmNews::getUserId, WmThreadLocalUtils.getUser().getId())
                .orderByDesc(WmNews::getCreatedTime);

        IPage<WmNews> page = new Page<WmNews>(wmNewsPageReqDto.getPage(),wmNewsPageReqDto.getSize());
        page(page,lqw);
        PageResponseResult pageResponseResult = new PageResponseResult((int)page.getCurrent(),(int)page.getSize(),(int)page.getTotal());
        pageResponseResult.setData(page.getRecords());
        return pageResponseResult;
    }

    @Override
    public void submit(WmNewsDto wmNewsDto) {
        //根据id判断是修改还是新增
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(wmNewsDto,wmNews);
        //自动类型匹配规则
        if(wmNewsDto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)){
            List<String> contentImageUrls = getImageUrls(wmNewsDto.getContent());
            if (contentImageUrls.size() > 0 && contentImageUrls.size() < 3) {
                wmNews.setImages(contentImageUrls.get(0));
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
            }
            if (contentImageUrls.size() >= 3) {
                String contentImageUrlsStr = contentImageUrls.toString();
                wmNews.setImages(contentImageUrlsStr.substring(1,contentImageUrlsStr.length()-1));
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
            }
            if(contentImageUrls.size() ==0){
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }
        }else{
//            String images = wmNewsDto.getImages().toString();
//            wmNews.setImages(images.substring(1,images.length()-1));
            wmNews.setImages(StringUtils.join(wmNewsDto.getImages(),","));

        }


        if(wmNewsDto.getId()!=null){
            //修改
                // 删除所有素材关联表中的数据
            wmNewsMaterialService.deleteByNewsId(wmNewsDto.getId());
                // 修改
            updateById(wmNews);
        }else{
            //新增
                 //新增
            wmNews.setUserId(Long.valueOf(WmThreadLocalUtils.getUser().getId()));
            wmNews.setCreatedTime(new Date());
            save(wmNews);
        }
        if (wmNewsDto.getStatus() == 0) {
            //是否为草稿
            //是
            return;
        }
            //否
        List<String> contentImageUrls = getImageUrls(wmNewsDto.getContent());
                //绑定素材和文章的关系
        wmNewsMaterialService.insertImage(contentImageUrls,wmNews.getId(), WemediaConstants.WM_CONTENT_REFERENCE);
                //绑定封面和文章的关系
        wmNewsMaterialService.insertImage(wmNewsDto.getImages(), wmNews.getId(), WemediaConstants.WM_COVER_REFERENCE);


    }

    private List<String> getImageUrls(String content) {
        log.info(content);
        List<String> imageUrls = new ArrayList<>();
        if (StringUtils.isNotBlank(content)) {
            List<Map> list = JSON.parseArray(content, Map.class);
            for (Map map : list) {
                if (map.get("type").equals("image")) {
                    imageUrls.add((String) map.get("value"));
                }
            }
        }
        log.info(imageUrls.toString());
        return imageUrls;

    }

    @Override
    public WmNews selectOne(Long id) {
        return query().eq("id", id).one();
    }
}
